package ext.generic.project.reports;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Vector;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.WTGroup;
import wt.org.WTUser;
import wt.ownership.OwnershipHelper;
import wt.projmgmt.admin.Project2;
import wt.query.QuerySpec;
import wt.util.WTContext;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTStandardDateFormat;

import com.ptc.projectmanagement.plan.Duration;
import com.ptc.projectmanagement.plan.PlanActivity;

import ext.com.iba.IBAUtil;
import ext.generic.project.reports.bean.PeopleUsageReportBean;

public class ExportPeopleUsage implements RemoteAccess {
	private static boolean VERBOSE;
	private static String CLASSNAME = ExportPeopleUsage.class.getName();
	private static String codebalocation;
	private static WTProperties wtProperties = null;
	/** 代表数组里的年、月、日 */
	private static final int Y = 0, M = 1, D = 2;

	static {
		try {
			wtProperties = WTProperties.getLocalProperties();
			VERBOSE = (WTProperties.getLocalProperties()).getProperty("ext.generic.project.reports.verbose", false);
			codebalocation = wtProperties.getProperty("wt.codebase.location", "");
		} catch (Throwable throwable) {
			throw new ExceptionInInitializerError(throwable);
		}

	}

	/**
	 * 输出调试信息
	 */
	private static void outDebugInfo(String info) {
		if (VERBOSE)
			System.out.println(CLASSNAME + "$$$$$" + info);
	}

	/**
	 * 资源负载报表
	 * @param startdate 开始时间
	 * @param enddate	结束时间
	 * @param userList	选择的组或者用户
	 * @param department	选择类型
	 * @return	EXCEL
	 * @throws WTException
	 * @throws IOException
	 */
	public static HSSFWorkbook exportToExcel(String startdate, String enddate, String userList,String department) throws WTException, IOException {
		if (!RemoteMethodServer.ServerFlag) {
			String method = "exportToExcel";
			try {
				HSSFWorkbook xf = (HSSFWorkbook) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[] { String.class, String.class, String.class ,String.class}, new Object[] { startdate, enddate, userList, department});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		

		String filePath = codebalocation + File.separator + "ext" + File.separator + "generic" + File.separator + "project" + File.separator + "reports" + File.separator + "pepleusageTemplate.xls";
		// 读取excel文件
		File file = new File(filePath);
		POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
		HSSFWorkbook hwb = new HSSFWorkbook(fs);
		
		// 获取用户列表
		Vector userVector = new Vector();
		StringTokenizer userListStrToken = new StringTokenizer(userList, ",");
		while (userListStrToken.hasMoreTokens()) {
			userVector.add(userListStrToken.nextToken());
		}
		if("usergroup".equals(department)){
			outDebugInfo("the select department is usergroup");
			Vector vecUserTemp=new Vector();
			ReferenceFactory rf = new ReferenceFactory();
			for(int k=0;k<userVector.size();k++){
				String groupRef = (String) userVector.get(k);
				WTGroup group = (WTGroup) rf.getReference(groupRef).getObject();
				outDebugInfo("group:>>>"+group.getName());
				TianmaProjectUtil.addUser(vecUserTemp, group);
			}
			outDebugInfo("vecUserTemp:>>>"+vecUserTemp);
			//userVector=vecUserTemp;//重新赋值
			writeToExcel(vecUserTemp, hwb, startdate, enddate);
			
		}else{
			Vector vecUserTemp=new Vector();
			ReferenceFactory rf = new ReferenceFactory();
			for (int j = 0; j < userVector.size(); j++) {
				// 获取用户
				// userusedinfo = new HashMap();
				String userRef = (String) userVector.elementAt(j);
				WTUser user = (WTUser) rf.getReference(userRef).getObject();
				vecUserTemp.add(user);
			}
			writeToExcel(vecUserTemp, hwb, startdate, enddate);
		}
		
		return hwb;
		
	}

	/**
	 * 资源负载报表
	 * @param userVector	用户列表
	 * @param hwb	excel
	 * @param startdate	开始时间
	 * @param enddate	完成时间
	 * @throws WTException
	 * @throws IOException
	 */
	public static void writeToExcel(Vector userVector,HSSFWorkbook hwb,String startdate ,String enddate)throws WTException, IOException{
		int numeric = 0;
		int rownum = 1;
		HSSFSheet sheet = hwb.getSheetAt(0);
		HSSFRow row = null;
		HSSFCell cell = null;
		Date startDate=null;
		Date endDate=null;
		if(startdate!=null){
			
			SimpleDateFormat f = new SimpleDateFormat("yyyy/MM/dd"); //格式化为 hhmmss
			try {
				startDate=f.parse(startdate);
				endDate=f.parse(enddate);
			} catch (ParseException e) {
				SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd"); //格式化为 hhmmss
				try {
					startDate=f2.parse(startdate);
					endDate=f2.parse(enddate);
				} catch (ParseException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
			}	
			
		}
		ArrayList alist = new ArrayList();
		// HashMap userusedinfo = new HashMap();
		if (userVector != null && userVector.size() > 0) {
			
			for (int j = 0; j < userVector.size(); j++) {
				// 获取用户
				WTUser user = (WTUser)userVector.elementAt(j);;
				String fullName = user.getFullName();
				outDebugInfo("user is =" + fullName);

				// 获取该人员所有负责的所有活动
				QueryResult rs = null;
				QuerySpec queryspec = new QuerySpec(PlanActivity.class);
				queryspec.appendWhere(OwnershipHelper.getSearchCondition(PlanActivity.class, user, true));
				rs = PersistenceHelper.manager.find(queryspec);
				row = sheet.getRow(rownum);
				// 循环活动，查找在搜索时间内活动
				while (rs.hasMoreElements()) {
					// 获取相关的任务信息
					PlanActivity activity = (PlanActivity) rs.nextElement();
					Project2 project2 = (Project2) activity.getContainer();

					String projectName = project2.getName() == null ? "" : project2.getName();

					String projectState = project2.getCtmState().getDisplay();// 项目状态

					String activityName = activity.getName();

					String activityState = activity.getHealthStatusType().getDisplay();// 任务状态

					outDebugInfo(project2.getName() + ">>>" + activity.getName());
					// 估计开始时间
					String activityStartDate = "";
					Timestamp getStartDate = activity.getStartDate();
					
					if (getStartDate != null) {
						activityStartDate = WTStandardDateFormat.format(getStartDate, "yyyy/MM/dd");
					}

					System.out.println("activityStartDate====" + activityStartDate);
					// 估计完成时间
					String activityEndDate = "";
					Timestamp getEndDate = activity.getFinishDate();
					if (getEndDate != null) {
						activityEndDate = WTStandardDateFormat.format(getEndDate, "yyyy/MM/dd");
					}
					
					// 实际开始时间
					String actualStartTimeStr = "";
					Timestamp actualStartTime = (Timestamp) IBAUtil.getIBAValue(activity, "ActualStartTime");
					if (actualStartTime != null) {
						actualStartTime.setHours(actualStartTime.getHours() + 8);
						actualStartTimeStr = WTStandardDateFormat.format(actualStartTime, "yyyy年MM月dd日");
					}

					// 实际完成时间
					String actualCompletionTimeStr = "";
					Timestamp actualCompletionTime = (Timestamp) IBAUtil.getIBAValue(activity, "ActualCompletionTime");
					if (actualCompletionTime != null) {
						actualCompletionTime.setHours(actualCompletionTime.getHours() + 8);
						actualCompletionTimeStr = WTStandardDateFormat.format(actualCompletionTime, "yyyy年MM月dd日");
					}

					outDebugInfo("选择的开始时间为:"+startDate+">>>活动开始时间为:"+getStartDate+">>>选择的结束时间为:"+endDate+">>>活动结束时间为:"+getEndDate);
					outDebugInfo(activityName+">>是否符合结果为:"+(getStartDate.after(startDate)&&getEndDate.before(endDate)));
				 if((getStartDate.after(startDate)&&getEndDate.before(endDate)))
				 {
					/*Long duration = activity.getDuration().getMillis();
					duration = duration / 28800000;
					outDebugInfo("工期=" + duration);*/
					Long totalworkhour = activity.getTotalEffort().getMillis();// 计划工时
					totalworkhour = totalworkhour / 3600000;
					outDebugInfo("总工时=" + totalworkhour);

					java.text.DecimalFormat df = new java.text.DecimalFormat("#0.00");
					// String dfworkhour = df.format(workhour);
					String dfworkhour = "";
					if(totalworkhour==0){
						dfworkhour="0 工时";
					}else{
						dfworkhour=df.format(totalworkhour)+" "+activity.getDoneEffort().getDurationFormat().getDisplay();// 计划工时
					}
					

					//Duration duration2 = activity.getDuration();
					Duration doneEffort = activity.getDoneEffort();
					
					outDebugInfo("doneEffort>>>>"+doneEffort);
					
					double dValue = doneEffort.getDuration(doneEffort.getDurationFormat());
					
					outDebugInfo("dValue>>>>"+dValue);
					
					//String dStr = dValue + " " + doneEffort.getDurationFormat().getDisplay();
					
					//outDebugInfo("dStr>>>>"+dStr);
					String doneWorkHour = "";
					if (doneEffort != null) {
						double dValue2 = doneEffort.getDuration(doneEffort.getDurationFormat());
						
						outDebugInfo("dValue2>>>>"+dValue2);
						if(dValue2==0){
							doneWorkHour="0 工时";
						}else{
							doneWorkHour = dValue + " " + doneEffort.getDurationFormat().getDisplay();
						}
						
						
						
						outDebugInfo("doneWorkHour>>>>"+doneWorkHour);
					}
					
					
					PeopleUsageReportBean purb = new PeopleUsageReportBean();
					purb.setUserName(fullName);// 用户名
					purb.setProductType(projectName);// 产品型号
					purb.setProjectState(projectState);// 项目状态
					purb.setActivityName(activityName);// 任务名称
					purb.setActivityState(activityState);// 任务状态
					purb.setPlanWorkHour(dfworkhour);// 计划工时
					purb.setAutalWorkHour(doneWorkHour);// 实际工时
					purb.setActualStartTime(actualStartTimeStr);// 实际开始时间
					purb.setActualCompletionTime(actualCompletionTimeStr);// 实际完成时间
					alist.add(purb);

					/*
					 * if(userusedinfo.containsKey(day)){
					 * outDebugInfo("=======进行累加======="); String
					 * sameuserduration = (String)userusedinfo.get(day);
					 * outDebugInfo("sameuserduration="+sameuserduration);
					 * double sameduration =
					 * Double.parseDouble(sameuserduration); workhour =
					 * sameduration+workhour;
					 * outDebugInfo("workhour="+workhour); dfworkhour =
					 * df.format(workhour); outDebugInfo("四舍五入2="+dfworkhour);
					 * userusedinfo.remove(day); userusedinfo.put(day,
					 * dfworkhour); }else{ userusedinfo.put(day, dfworkhour); }
					 */
					// }
				}
			  }
			}
		}

		System.out.println("alist.size()>>>>" + alist.size());
		for (int k = 0; k < alist.size(); k++) {
			PeopleUsageReportBean purb = (PeopleUsageReportBean) alist.get(k);
			numeric = numeric + 1;
			// 写入表头

			row = sheet.createRow(rownum);
			int cellnum = 0;
			// 全名
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getUserName());
			cellnum++;

			// 产品型号
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getProductType());
			cellnum++;

			// 项目状态
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getProjectState());
			cellnum++;

			// 任务名称
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getActivityName());
			cellnum++;

			// 任务状态
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getActivityState());
			cellnum++;

			// 计划工时
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getPlanWorkHour());
			cellnum++;

			// 汇报工时
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getAutalWorkHour());
			cellnum++;

			// 实际开展日期
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getActualStartTime());
			cellnum++;

			// 实际完成日期
			cell = row.createCell(cellnum);
			cell.setCellValue(purb.getActualCompletionTime());
			rownum = rownum + 1;
		}

		//return hwb;
	}
	/**
	 * 将年/月/日转换为Timestamp
	 * 
	 * @WTException null
	 **/

	public static Timestamp StrToTimestamp(String timestampStr) throws WTException {
		SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = df1.format(Date.parse(timestampStr));
		Timestamp CreateDate = Timestamp.valueOf(time);
		return CreateDate == null ? null : CreateDate;
	}

	/**
	 * 获取时间的年月日的显示字符串
	 * 
	 * @param time
	 *            需要获取时间的时间戳
	 * @return 时间相关的显示字符串值,格式为年-月-日
	 * @exception null
	 **/
	private static String getTimeStampDateStr(Timestamp time) {
		if (time == null)
			return "";
		TimeZone tz = WTContext.getContext().getTimeZone();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		formatter.setTimeZone(tz);
		String dateString = formatter.format(time);
		return dateString;
	}
}
